'use client';

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { FileSpreadsheet, Settings, MapPin, Database, Download, Loader2, User, Lock, Edit3 } from 'lucide-react';
import type { ParsedExcelFile } from '@/lib/excel-parser.client';
import { 
  ExcelAnalyzer, 
  EntityObject, 
  GeneratedParameterTable, 
  ClassificationStandard 
} from '@/lib/excel-analyzer';
import { useSearchParams } from 'next/navigation';
import { canEditByRole, getPermissionDescription, isEditDisabled } from '@/lib/data-entry-permissions';

// 解析工作表内的子表
const parseSubTables = (sheet: any) => {
  const subTables: Array<{name: string, startRow: number, endRow: number, data: any[]}> = [];
  
  // 首先检查headers中是否有表标题
  if (sheet.headers && sheet.headers[0] && typeof sheet.headers[0] === 'string' && sheet.headers[0].includes('表 C.')) {
    const tableName = sheet.headers[0].trim();
    subTables.push({
      name: tableName,
      startRow: 0,
      endRow: sheet.rows.length - 1,
      data: sheet.rows
    });
  }
  
  // 然后在rows中查找其他子表
  for (let i = 0; i < sheet.rows.length; i++) {
    const row = sheet.rows[i];
    if (row && row[0] && typeof row[0] === 'string' && row[0].includes('表 C.')) {
      // 找到子表标题
      const tableName = row[0].trim();
      const startRow = i;
      
      // 找到下一个子表的开始位置或工作表结束
      let endRow = sheet.rows.length - 1;
      for (let j = i + 1; j < sheet.rows.length; j++) {
        const nextRow = sheet.rows[j];
        if (nextRow && nextRow[0] && typeof nextRow[0] === 'string' && nextRow[0].includes('表 C.')) {
          endRow = j - 1;
          break;
        }
      }
      
      // 提取子表数据
      const tableData = sheet.rows.slice(startRow, endRow + 1);
      subTables.push({
        name: tableName,
        startRow,
        endRow,
        data: tableData
      });
    }
  }
  
  return subTables;
};

// 工作表分组函数 - 按01015标准分组并解析子表
const groupSheetsByRange = (sheets: any[]) => {
  const groups: Record<string, any[]> = {};
  
  // 筛选C开头的工作表
  const cSheets = sheets.filter(sheet => sheet.sheetName.startsWith('C'));
  
  if (cSheets.length === 0) return {};
  
  // 处理每个C开头的工作表
  cSheets.forEach(sheet => {
    const sheetName = sheet.sheetName;
    
    // 解析工作表内的子表
    const subTables = parseSubTables(sheet);
    
    if (subTables.length > 0) {
      // 如果有子表，将子表作为独立项目
      groups[sheetName] = subTables.map(subTable => {
        // 查找实际的表头行
        let actualHeaders = [];
        let actualRows = subTable.data;
        
        // 查找包含"序号"、"中文名称"等关键词的行作为表头
        for (let i = 0; i < Math.min(3, subTable.data.length); i++) {
          const row = subTable.data[i];
          if (row && row[0] && typeof row[0] === 'string' && 
              (row[0].includes('序号') || row[0].includes('中文名称') || row[0].includes('属性名称'))) {
            actualHeaders = row;
            actualRows = subTable.data.slice(i + 1); // 表头之后的数据
            break;
          }
        }
        
        // 如果没找到合适的表头，使用第一行
        if (actualHeaders.length === 0 && subTable.data.length > 0) {
          actualHeaders = subTable.data[0];
          actualRows = subTable.data.slice(1);
        }
        
        return {
          sheetName: subTable.name,
          parentSheet: sheetName,
          rows: actualRows,
          headers: actualHeaders,
          isSubTable: true
        };
      });
    } else {
      // 如果没有子表，将整个工作表作为一个项目
      groups[sheetName] = [{
        sheetName: sheetName,
        parentSheet: sheetName,
        rows: sheet.rows,
        headers: sheet.headers,
        isSubTable: false
      }];
    }
  });
  
  return groups;
};

export default function ExcelAnalysisPage() {
  const [classificationData, setClassificationData] = useState<ParsedExcelFile | null>(null);
  const [loading, setLoading] = useState(false);
  const [selectedClassificationSheet, setSelectedClassificationSheet] = useState<string>('');
  const [selectedSheetGroup, setSelectedSheetGroup] = useState<string>('');
  const [currentUserRole, setCurrentUserRole] = useState<string>('');
  const [inputData, setInputData] = useState<Record<string, string>>({});
  const [isEditMode, setIsEditMode] = useState(false);
  const searchParams = useSearchParams();

  // 获取当前用户角色
  useEffect(() => {
    const userStr = typeof window !== 'undefined' ? localStorage.getItem("currentUser") : null;
    if (userStr) {
      try {
        const user = JSON.parse(userStr);
        setCurrentUserRole(user.role || 'guest');
      } catch {
        setCurrentUserRole('guest');
      }
    } else {
      setCurrentUserRole('guest');
    }
  }, []);

  // 处理输入框数据变化
  const handleInputChange = (rowIndex: number, columnIndex: number, value: string) => {
    const key = `${rowIndex}-${columnIndex}`;
    setInputData(prev => ({
      ...prev,
      [key]: value
    }));
  };

  // 获取数据来源的样式类
  const getDataSourceBadgeColor = (dataSource: string) => {
    switch (dataSource) {
      case 'E': return 'bg-blue-500 text-white';
      case 'P': return 'bg-green-500 text-white';
      case 'C': return 'bg-orange-500 text-white';
      case 'O': return 'bg-purple-500 text-white';
      case 'R': return 'bg-red-500 text-white';
      default: return 'bg-gray-500 text-white';
    }
  };

  // 获取数据来源的描述
  const getDataSourceDescription = (dataSource: string) => {
    switch (dataSource) {
      case 'E': return '设计阶段数据';
      case 'P': return '采购阶段数据';
      case 'C': return '施工数据';
      case 'O': return '建设数据';
      case 'R': return '运维记录数据';
      default: return '未知来源';
    }
  };

  // 加载Excel文件
  const loadExcelFile = async (filename: string) => {
    try {
      const encodedFilename = encodeURIComponent(filename);
      const response = await fetch(`/api/excel?filename=${encodedFilename}`);
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '加载文件失败');
      }
      return await response.json() as ParsedExcelFile;
    } catch (error) {
      console.error('加载Excel文件失败:', error);
      throw error;
    }
  };

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      setLoading(true);
      try {
        // 使用0606文件作为主要数据源（特定表格会自动应用0618数据更新）
        const classification = await loadExcelFile('06-06/0606-石楼油库实体对象分类表.xlsx');
        
        setClassificationData(classification);
        
        // 设置默认选中的分类工作表
        const cSheets = classification.sheets.filter(sheet => 
          sheet.sheetName.startsWith('C')
        );
        
        // 按组分类工作表并设置默认选择
        if (cSheets.length > 0) {
          const groups = groupSheetsByRange(cSheets);
          
          // 检查URL参数
          const urlGroup = searchParams.get('group');
          const urlCode = searchParams.get('code');
          const urlType = searchParams.get('type');
          
          if (urlGroup && groups[urlGroup]) {
            // 使用URL参数指定的组
            setSelectedSheetGroup(urlGroup);
            
            if (urlCode) {
              // 在指定组中查找包含指定分类码的工作表
              const targetSheets = groups[urlGroup];
              const targetIndex = targetSheets.findIndex(sheet => 
                sheet.sheetName.includes(urlCode) || 
                sheet.headers.some((header: string) => header && header.includes(urlCode))
              );
              
              if (targetIndex >= 0) {
                setSelectedClassificationSheet(`${targetSheets[targetIndex].parentSheet}-${targetIndex}`);
              } else {
                // 如果没找到具体的表，使用该组的第一个表
                setSelectedClassificationSheet(`${targetSheets[0].parentSheet}-0`);
              }
            } else {
              // 如果没有指定具体的分类码，使用该组的第一个表
              setSelectedClassificationSheet(`${groups[urlGroup][0].parentSheet}-0`);
            }
          } else {
            // 没有URL参数，使用默认选择
            const firstGroupKey = Object.keys(groups)[0];
            if (firstGroupKey && groups[firstGroupKey].length > 0) {
              setSelectedSheetGroup(firstGroupKey);
              setSelectedClassificationSheet(`${groups[firstGroupKey][0].parentSheet}-0`);
            }
          }
        }
      } catch (error) {
        console.error('初始化数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    initializeData();
  }, [searchParams]);

  if (loading) {
    return (
      <div className="container mx-auto p-6">
        <Card>
          <CardContent className="flex items-center justify-center p-8">
            <div className="text-center">
              <Loader2 className="h-8 w-8 mx-auto mb-2 animate-spin" />
              <p>正在加载和分析Excel文件...</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* 用户权限状态卡片 */}
      {currentUserRole && (
        <Card className="border-l-4 border-l-blue-500">
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-sm">
              <User className="h-4 w-4" />
              当前用户权限
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <Badge variant="outline" className="text-sm">
                  {getPermissionDescription(currentUserRole)}
                </Badge>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setIsEditMode(!isEditMode)}
                  className="flex items-center gap-2"
                >
                  {isEditMode ? <Lock className="h-4 w-4" /> : <Edit3 className="h-4 w-4" />}
                  {isEditMode ? '锁定编辑' : '开启编辑'}
                </Button>
              </div>
              <div className="text-xs text-muted-foreground">
                只能录入特定数据来源的属性数据
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 权限说明卡片 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Settings className="h-5 w-5" />
            数据录入权限说明
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            <div className="text-center">
              <Badge className="bg-blue-500 mb-2">E</Badge>
              <p className="text-sm font-medium">设计阶段数据</p>
              <p className="text-xs text-muted-foreground">设计用户可录入</p>
            </div>
            <div className="text-center">
              <Badge className="bg-green-500 mb-2">P</Badge>
              <p className="text-sm font-medium">采购阶段数据</p>
              <p className="text-xs text-muted-foreground">采购用户可录入</p>
            </div>
            <div className="text-center">
              <Badge className="bg-orange-500 mb-2">C</Badge>
              <p className="text-sm font-medium">施工数据</p>
              <p className="text-xs text-muted-foreground">施工用户可录入</p>
            </div>
            <div className="text-center">
              <Badge className="bg-purple-500 mb-2">O</Badge>
              <p className="text-sm font-medium">建设数据</p>
              <p className="text-xs text-muted-foreground">施工用户可录入</p>
            </div>
            <div className="text-center">
              <Badge className="bg-red-500 mb-2">R</Badge>
              <p className="text-sm font-medium">运维记录数据</p>
              <p className="text-xs text-muted-foreground">施工用户可录入</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {classificationData && (
        <Card>
          <CardHeader>
            <CardTitle>01015规范实体对象分类属性表</CardTitle>
          </CardHeader>
          <CardContent>
            {(() => {
              // 筛选C开头的工作表并按组分类
              const cSheets = classificationData.sheets.filter(sheet => 
                sheet.sheetName.startsWith('C')
              );
              const sheetGroups = groupSheetsByRange(cSheets);
              const currentGroupSheets = selectedSheetGroup ? sheetGroups[selectedSheetGroup] || [] : [];
              
              // 查找当前选中的子表
              let currentSheet = null;
              if (selectedClassificationSheet) {
                const parts = selectedClassificationSheet.split('-');
                if (parts.length >= 2) {
                  const index = parseInt(parts[parts.length - 1]);
                  if (!isNaN(index) && currentGroupSheets[index]) {
                    currentSheet = currentGroupSheets[index];
                  }
                }
              }
              
              return (
                <>
                 
                  
                  {/* 顶部：分类组标签 */}
                  <div className="mb-6">
                    <Tabs value={selectedSheetGroup} onValueChange={(value) => {
                      setSelectedSheetGroup(value);
                      // 选择该组的第一个子表
                      const firstSheet = sheetGroups[value]?.[0];
                      if (firstSheet) {
                        setSelectedClassificationSheet(`${firstSheet.parentSheet}-0`);
                      } else {
                        setSelectedClassificationSheet('');
                      }
                    }}>
                      <TabsList className="mb-4 flex-wrap h-auto">
                        {Object.keys(sheetGroups).map((groupKey) => (
                          <TabsTrigger key={groupKey} value={groupKey} className="text-sm">
                            {groupKey} ({sheetGroups[groupKey].length}个表)
                          </TabsTrigger>
                        ))}
                      </TabsList>
                    </Tabs>
                  </div>
                  
                  {/* 下方：左右分栏 */}
                  <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* 左侧：工作表清单 */}
                    <div className="lg:col-span-1">
                      <Card className="h-[700px] flex flex-col">
                        <CardHeader className="flex-shrink-0">
                          <CardTitle className="text-sm flex items-center gap-2">
                            <FileSpreadsheet className="h-4 w-4" />
                            {selectedSheetGroup ? `${selectedSheetGroup} 工作表清单` : '工作表清单'}
                          </CardTitle>
                        </CardHeader>
                        <CardContent className="flex-1 overflow-hidden">
                          <div className="h-full overflow-y-auto space-y-2 pr-2">
                            {currentGroupSheets.map((sheet, index) => (
                              <Button
                                key={`${sheet.parentSheet}-${index}`}
                                variant={selectedClassificationSheet === `${sheet.parentSheet}-${index}` ? "default" : "outline"}
                                className="w-full justify-start text-left h-auto p-3"
                                onClick={() => setSelectedClassificationSheet(`${sheet.parentSheet}-${index}`)}
                              >
                                <div className="flex flex-col items-start w-full">
                                  <div className="font-medium text-sm leading-tight">{sheet.sheetName}</div>
                                  <div className="text-xs text-muted-foreground mt-1">
                                    {(() => {
                                      // 对表 C.14 应用行数过滤，只显示前6行
                                      const isC14 = sheet.sheetName && sheet.sheetName.includes('C.14');
                                      const displayRows = isC14 ? Math.min(6, sheet.rows.length) : sheet.rows.length;
                                      return `${displayRows} 行 × ${sheet.headers.length} 列`;
                                    })()} 
                                  </div>
                                  {sheet.isSubTable && (
                                    <div className="text-xs text-blue-600 mt-1">
                                      来自: {sheet.parentSheet}
                                    </div>
                                  )}
                                </div>
                              </Button>
                            ))}
                            
                            {!selectedSheetGroup && (
                              <div className="flex items-center justify-center h-full">
                                <div className="text-center text-muted-foreground">
                                  <FileSpreadsheet className="h-12 w-12 mx-auto mb-4 opacity-50" />
                                  <p>请先从顶部选择一个分类组</p>
                                </div>
                              </div>
                            )}
                            
                            {selectedSheetGroup && currentGroupSheets.length === 0 && (
                              <div className="flex items-center justify-center h-full">
                                <div className="text-center text-muted-foreground">
                                  <FileSpreadsheet className="h-12 w-12 mx-auto mb-4 opacity-50" />
                                  <p>该组内暂无工作表</p>
                                </div>
                              </div>
                            )}
                          </div>
                        </CardContent>
                      </Card>
                    </div>
                    
                    {/* 右侧：工作表内容 */}
                    <div className="lg:col-span-2">
                      {currentSheet ? (
                        <Card className="h-[700px] flex flex-col">
                          <CardHeader className="flex-shrink-0">
                            <CardTitle className="text-sm">
                              {currentSheet.sheetName} - 表结构预览
                            </CardTitle>
                            <div className="flex gap-2">
                              <Badge variant="outline">
                                数据行数: {(() => {
                                  // 对表 C.14 应用行数过滤，只显示前6行
                                  const isC14 = currentSheet.sheetName && currentSheet.sheetName.includes('C.14');
                                  return isC14 ? Math.min(6, currentSheet.rows.length) : currentSheet.rows.length;
                                })()}
                              </Badge>
                              <Badge variant="outline">
                                列数: {currentSheet.headers.length}
                              </Badge>
                              {isEditMode && (
                                <Badge className="bg-blue-500">
                                  可编辑模式
                                </Badge>
                              )}
                            </div>
                          </CardHeader>
                          <CardContent className="flex-1 overflow-hidden">
                            <div className="h-full overflow-auto border rounded-md">
                              <Table>
                                <TableHeader className="sticky top-0 bg-background z-10">
                                  <TableRow>
                                    {currentSheet.headers.map((header: any, index: number) => (
                                      <TableHead key={index} className="min-w-[120px] font-semibold border-r">
                                        {header}
                                        {header === '数据来源' && (
                                          <div className="text-xs text-muted-foreground mt-1">权限控制</div>
                                        )}
                                      </TableHead>
                                    ))}
                                  </TableRow>
                                </TableHeader>
                                <TableBody>
                                  {(() => {
                                    // 对表 C.14 应用行数过滤，只显示前6行
                                    const isC14 = currentSheet.sheetName && currentSheet.sheetName.includes('C.14');
                                    const filteredRows = isC14 ? currentSheet.rows.slice(0, 6) : currentSheet.rows;
                                    
                                    return filteredRows.map((row: any, rowIndex: number) => (
                                      <TableRow key={rowIndex} className="hover:bg-muted/50">
                                        {currentSheet.headers.map((_: any, cellIndex: number) => {
                                          const cellValue = row[cellIndex]?.toString() || '';
                                          const isDataSourceColumn = currentSheet.headers[cellIndex] === '数据来源';
                                          const dataSource = isDataSourceColumn ? cellValue : row[currentSheet.headers.indexOf('数据来源')] || '';
                                          const canEdit = canEditByRole(currentUserRole, dataSource);
                                          const isDisabled = !isEditMode || isEditDisabled(currentUserRole, dataSource);
                                          
                                          return (
                                            <TableCell key={cellIndex} className="min-w-[120px] border-r">
                                              {isDataSourceColumn ? (
                                                <div className="flex flex-col gap-1">
                                                  <Badge className={getDataSourceBadgeColor(cellValue)}>
                                                    {cellValue}
                                                  </Badge>
                                                  <div className="text-xs text-muted-foreground">
                                                    {getDataSourceDescription(cellValue)}
                                                  </div>
                                                  {!canEdit && (
                                                    <div className="text-xs text-red-600 flex items-center gap-1">
                                                      <Lock className="h-3 w-3" />
                                                      无权限
                                                    </div>
                                                  )}
                                                </div>
                                              ) : isEditMode && cellIndex > 0 && cellIndex !== currentSheet.headers.indexOf('数据来源') ? (
                                                <Input
                                                  value={inputData[`${rowIndex}-${cellIndex}`] || cellValue}
                                                  onChange={(e) => handleInputChange(rowIndex, cellIndex, e.target.value)}
                                                  disabled={isDisabled}
                                                  className={isDisabled ? 'bg-gray-100 cursor-not-allowed text-gray-500 text-sm' : 'text-sm'}
                                                  placeholder={isDisabled ? '无编辑权限' : '请输入内容'}
                                                />
                                              ) : (
                                                cellValue
                                              )}
                                            </TableCell>
                                          );
                                        })}
                                      </TableRow>
                                    ));
                                  })()}
                                </TableBody>
                              </Table>
                            </div>
                          </CardContent>
                        </Card>
                      ) : (
                        <Card className="h-[700px] flex flex-col">
                          <CardContent className="flex-1 flex items-center justify-center">
                            <div className="text-center">
                              <FileSpreadsheet className="h-16 w-16 mx-auto mb-4 text-muted-foreground opacity-50" />
                              <p className="text-muted-foreground text-lg mb-2">请选择一个工作表查看内容</p>
                              {selectedSheetGroup && (
                                <p className="text-sm text-muted-foreground">
                                  当前分类组：{selectedSheetGroup}
                                </p>
                              )}
                            </div>
                          </CardContent>
                        </Card>
                      )}
                    </div>
                  </div>
                </>
              );
            })()}
          </CardContent>
        </Card>
      )}
    </div>
  );
} 